<script setup>

import {onBeforeUnmount, onMounted, reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import {getChatList, getChatUser} from "@/api/chat.js";
import {user} from "@/stores/counter.js";
//region chat
const chats = ref([])
const users = ref([])
let client = ref(null);
const curUser = user()
onMounted(() => {
  watch(() => route.query, (newQuery, oldQuery) => {
    if (newQuery !== oldQuery) {
      // 当路由参数变化时，关闭旧的 WebSocket 连接
      if (client.value) {
        client.value.close();
      }

      // 创建新的 WebSocket 连接
      client = ref(new WebSocket(`ws://localhost:7000/websocket/api1/${curUser.userId}/${newQuery.id}`));
      client.value.onopen = () => {
        console.log("连接成功");
      };
      client.value.onmessage = (msg) => {
        console.log(msg);
        chats.value.push(JSON.parse(msg.data));
      };
      client.value.onclose = () => {
        console.log("连接关闭");
      };

      // 获取聊天列表
      getChatList(newQuery.id).then((res) => {
        chats.value = res.data;
      });
    }
  }, {immediate: true});
})
// immediate: true 选项会在初始化时立即触发一次回调函数

getChatUser().then((res) => {
  users.value = res.data
})

onBeforeUnmount(() => {
  if (client.value) {
    client.value.close()
  }
})
//endregion

//region main
const route = useRoute()
// 用户提问
const questions = reactive([])
// AI回答
const answers = reactive([])

const chatlist = ref([
  {
    type: 0,
    content: '你好'
  },
  {
    type: 1,
    content: '你好'
  }, {
    type: 0,
    content: '我想请问一下'
  }
])
const input = ref('');
const isLoading = ref(false)
const handleSubmit = () => {
  if (isLoading === true) {
    ElMessage.error("请勿重复提问...")
    return;
  }
  isLoading.value = true
  if (client.value) {
    if(input.value.trim().length === 0){
      ElMessage.error("请输入内容")
      isLoading.value = false
    }else {
      client.value.send(input.value)
      isLoading.value = false
      chats.value.push({
        type: 1,
        content: input.value
      })
    }
  }
  input.value = ""
}
//endregion
</script>

<template>

  <!-- 总容器 -->
  <div class="wrapper">

    <header>
      <i class="fa fa-angle-left" onclick="history.go(-1)"></i>
      <p>{{ route.query.name }}医生</p>
      <div></div>
    </header>
    <div class="top-ban"></div>

    <div class="chat-area">

      <div>
        <div class="chat-area">
          <!--聊天提示-->
          <div align="center">
            <div class="tip">
              请保持网络连接畅通，等待医生接入。
            </div>
            <div class="tip">
              问诊前，请准备好您的病情描述和相关检查报告。
            </div>
            <div class="tip">
              我们承诺保护您的隐私信息，问诊内容将严格保密
            </div>
          </div>
          <!--对话内容-->
          <div v-for="(item,index) in chats" :key="index">
            <div class="ai-message-item" v-if="item.type==2">
              <div class="ai-message">
                {{ item.content }}
              </div>
            </div>
            <div class="user-message-item" v-else>
              <div class="user-message">
                {{ item.content }}
              </div>
            </div>
          </div>
          <div style="height: 10vh;background-color: transparent"/>
        </div>
        <!-- inputArea-->
        <div class="input-box">
          <el-input placeholder="请输入对话内容"
                    @keyup.enter="handleSubmit"
                    v-model="input"
                    clearable size="large" style="padding: 2vh 1vw 2vh 1vw;">
            <template #append>
              <el-button @click="handleSubmit" v-loading="isLoading">
                <template #icon>
                  <i class="fa fa-send"></i>
                </template>
              </el-button>
            </template>
          </el-input>
        </div>


      </div>
    </div>

  </div>


</template>

<style scoped>
@import "@/assets/css/appointment.css";
@import "@/assets/framework/reset.css";
@import "@/assets/framework/font-awesome/css/font-awesome.min.css";

body {
  scale: 50%;
}

.input-box {
  padding: 0vh 0vw 5vh 0vw;
  width: 100%;
  height: 10vw;
  position: fixed;
  bottom: 0;
  background-color: #f2f2f2;
}


.tip {
  margin-top: 1vh;
  width: 80vw;
  font-size: xx-small;
  background-color: #c5c5c5;
  color: #FFFFFF;
  padding: 1vw;
}

.ai-message {
  background-color: #FFFFFF;
  font-size: 2.25vh;
  box-shadow: 0 0 1vw 0 rgba(0, 0, 0, 0.3);
  margin: 2vh 5vw 2vh 5vw;
  padding: 1.25vh;
  border-radius: 1vw;
}

.ai-message-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: stretch
}

.user-message {
  background-color: #3D96F2;
  color: #FFFFFF;
  font-size: 2.25vh;
  box-shadow: 0 0 1vw 0 rgba(0, 0, 0, 0.3);
  margin: 2vh 5vw 2vh 5vw;
  padding: 1.25vh;
  border-radius: 1vw;
}

.user-message-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-end;
  align-items: flex-start;
  align-content: stretch
}

.myicon {
  scale: 200%;
}

body {
  font-family: "Microsoft YaHei", sans-serif;
}

</style>